//
//  RequestService+iap.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/3.
//

import Foundation
import Alamofire
import Swime
extension RequestService {
    func vipProduct(completeClosure: (([ProductModel]) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)"])
        session.request("\(apiHost)/api/user/vipProduct",
                        method: .post,
                        parameters: ["sign":sign,
                                     "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)",
                                     "systemId":system_id]
        ).responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200", let result = jsonDic["result"] as? [[String :Any]], var models = [ProductModel].deserialize(from: result) else { return }
                if !models.isEmpty {
                    models[0]?.isSelect = true
                }
                completeClosure?(models.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error.errorDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func scoreProduct(completeClosure: (([ProductModel]) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)"])
        session.request("\(apiHost)/api/user/scoreProduct",
                        method: .post,
                        parameters: ["sign":sign,
                                     "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)",
                                     "systemId":system_id]
        ).responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200", let result = jsonDic["result"] as? [[String :Any]], var models = [ProductModel].deserialize(from: result) else { return }
                if !models.isEmpty {
                    models[0]?.isSelect = true
                }
                completeClosure?(models.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error.errorDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func iapVerfiryWithOrderNo(orderNo:String, receiptData:String, completeClosure: (([String: Any], Int) -> Void)?, failureClosure: ((AFError) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)",
                                                               "orderNo":orderNo,
                                                               "receiptData":receiptData])
        session.request("\(apiHost)/api/pay/checkAppleOrder",
                        method: .post,
                        parameters: ["sign":sign,
                                     "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)",
                                     "systemId":system_id,
                                     "orderNo":orderNo,
                                     "receiptData":receiptData]
        ).responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any] else { return }
                if let code = jsonDic["code"] as? String {
                    completeClosure?([:], Int(code) ?? 0)
                }else {
                    completeClosure?([:], 0)
                }
            case let .failure(error):
                failureClosure?(error)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func iapCreateOrder(productId:String, completeClosure: (([String: Any], Int) -> Void)?, failureClosure: ((AFError) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)",
                                                               "productId":productId])
        session.request("\(apiHost)/api/pay/apple",
                        method: .post,
                        parameters: ["sign":sign,
                                     "userId":"\(Appearance.shared.accoutModel?.userId ?? 0)",
                                     "systemId":system_id,
                                     "productId":productId]
        ).responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String,
                      let result = jsonDic["result"] as? [String :Any] else { return }
                completeClosure?(result, Int(current) ?? 0)
            case let .failure(error):
                failureClosure?(error)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func order_list(types:String, page:Int, completeClosure: (([RechargeItemModel]) -> Void)?, failureClosure: ((AFError) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "types":types,
                                                               "page":"\(page)"])
        session.request("\(apiHost)/api/user/order_list",
                        method: .post,
                        parameters: ["sign":sign,
                                     "timestamp":time,
                                     "types":types,
                                     "page":"\(page)"]
        ).responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String,
                      let result = jsonDic["result"] as? [String :Any], let content = result["content"] as? [[String: Any]], let models = [RechargeItemModel].deserialize(from: content) else { return }
                completeClosure?(models.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
}
